I am learning to work with Parse API and found this tutorial which uses handlebars.js for templating. Since I am comfortable with jQuery and have no experience in YUI so I am trying to simply re-write the above tutorial in jQuery.
But I am stuck in the following part:
var content = Y.Lang.sub(Y.one('#todo-items-template').getHTML(), {
content: item.get('content'),
id: item.id,
isComplete: item.get('isComplete')
});
where, content, id and isComplete are fields in Parse web store.
Now, my question is: what is the jQuery equivalent of above Lang.sub YUI function.
Here's the very basics, adapt or extend to your needs:
$.sub = function(str, obj) {
return str.replace(/\{([^}]+)\}/g, function(_, m) {
return obj[m];
});
};
console.log($.sub('Hello {foo}', { foo: 'World' }));
//=> Hello World
I would suggest pulling in the Handlebars JS repository; It's a very popular solution and is very powerful. Since it's popular, it's probably a good idea to learn how to use it since you'll likely be running into again in the future.
Other templating frameworks are listed here: http://microjs.com/#templating
Related
I'm trying to build a new conditional helper for my Ember application.
Is important mention that I'm using Ember 1.10.1 that uses Handlebars 2.0 and I can't upgrade it, would be great solving the problem with this version of Ember.
Before writing here I tried different solutions and debugged the Ember code a lot, I'm near to the solution but probably I'm missing something.
First of all, I tried with the following approach reading the Handlebar documentation:
Ember.Handlebars.registerHelper('helperName', function(conditional, options) {
if(conditional) {
return options.fn(this);
} else {
return options.inverse(this);
}
});
And here the template:
{{#helperName booleanCondition}}
print true
{{else}}
print false
{{/helperName}}
Everything worked fine calling the fn function but the inversion function (used to render the template of the else branch) was actually an object instead of a function.
Then I started debugging the Ember code and I tried to follow the same approach that Ember uses with the if helper, so I ended up with the following:
Ember.Handlebars.registerHelper('helperName', function(condition, options) {
var permission = Ember.Object.extend({
can: Ember.computed(function() {
return condition;
})
}).create();
Ember.Handlebars.helpers.boundIf.helperFunction.call(this, ["can"], permission, options, options.data.buffer);
});
can is the property bound to the if, used to change the template if the property changes, since we are using the boundIf version of the if (that does what I just said).
The problem of this solution, that imho could be the nearest to be correct, is that the property is not computed correctly and the helper prints always the false value.
I debugged really a lot without making it working, so any help would be very appreciated and I hope this could be useful for someone else as well.
If what you're trying to do is build a conditional approach that supports authorization questions, you should take a look at ember-can. It is an Ember-CLI addon (whereas it looks like you are doing globals) but older versions worked with Ember 1.10. You should be able to reference what they do there and pull it in on your setup
The good news is you are on Ember 1.10!
This means you have subexpressions. And its simple to create a bound non-block helper:
Ember.HTMLBars._registerHelper('foo', function(bar) {
return bar == 'bar';
});
To use it as a block helper combine it with the {{#if}} helper:
{{#if (foo model)}}
in if
{{else}}
in else
{{/if}}
I will be developing a large, AMD-based javascript application, structured with backbone.js and potentially require.js. I am doing research on the best way to go, and one thing I would like to get into using is a template library, particularly handlebars.js.
My problem here is that I want to make javascript-only modules that can be loaded and implemented on the fly, well after the application is loaded. Templates are based on HTML tags, but I don't want to include html pages after the fact.
My question is: Is it stupid, or valid practice to mock up HTML templates as strings in your javascript, and then render them? I feel like it would kill the entire point in performance alone, but I really don't know.
This is an example of what I am talking about:
var render = function(html, model) {
var tmpl = Handlebars.compile(html);
return tmpl(model);
}
$(document).ready(function() {
var template = '<div class="entry">' +
'<h1>{{title}}</h1>' +
'<div class="body">{{body}}</div>' +
'</div>';
var model = {
title: 'I love templating,',
body: 'And so do you!'
}
template = render(template, model);
$(document.body).append(template);
});
Is this terrible practice, or is there a better way to implement this in a javascript-only application?
Template are used to separate html from javascript code.
I suggest you to look at requireJS text plugin to load your template code in an AMD environment.
I have been trying out some different ways to organize my code in my javascript applications and i wonder which one is the most appropriate.
First example:
var Application = {
init: function() {
//Some code
Calculate();
},
Calculate: function() {
//Some code
}
};
Second example:
(function() {
function init() {
//Some code
Calculate();
}
function Calculate() {
//Some code
}
})();
Third example:
(function() {
var init = function() {
//Some code
Calculate();
};
var Calculate = function() {
//Some code
};
})();
Or is it some other way that is preferred? I get very confused over this. Thanks in advance!
The answer is, without question, "it depends." How big is your application? Do you need all of the modules all of the time? How scalable and reusable does your app need to be? These are not JavaScript questions specifically, but rather "architectural" questions, and while learning JavaScript basics is relatively easy, it takes a lot of years to learn to be a good architect in software development. (though it is excellent that you are asking these questions.)
I would encourage you to dive into programming patterns. Learning patterns is learning to structure an application in the right way, depending on the given application.
I can say that a combination of your first example and your second example are a good place to start (an instantly invoked function expression wrapping and returning an object literal). This gives a degree of private scope via closure, and is called the Module Pattern. You will see this pattern used to some degree in almost all major JS applications and libraries because of its versatility and elegance.
To learn more about JavaScript patterns, I highly recommend Addy Osmani's "Learning JavaScript Design Patterns." You can read it for free, here: http://addyosmani.com/resources/essentialjsdesignpatterns/book/
Google Chrome extensions using manifest_version: 2 are restricted from using eval or new Function. All of the JavaScript templating libraries I checked (mustachejs, underscorejs, jQuery template, hoganjs, etc) use new Function. Are there any that are fairly mature and supported that don't use either?
Info about the security restrictions.
It turns out that mustachejs added new Function recently and using tag 0.4.2 doesn't have it. It the API is slightly different with Mustache.to_html instead of Mustache.render and there are likely some performance reduction.
I opened an issue to potentially get new Function removed in a future release.
It doesn't appear that Pure uses either eval or new Function.
The answers here are outdated so I post an update.
Since September, Google changed their policy and allowed unsafe-eval in manifest 2 extensions. See this thread and this page.
So libraries using eval(), new Function() etc. can be used if unsafe-eval is turned on for your extensions.
Closure Templates is a templating library that does not use eval. Templates are compiled to JavaScript ahead of time, so that what gets included in your app is a plain .js file that should not run into CSP issues.
Distal template doesn't use eval.
It really depends on what you mean by "template library". If you just want string interpolation, there's no need for eval or new Function, when you start needing embedded looping structures, things get more complicated.
A few months ago I wrote a String.prototype.tmpl.js script that I've used a couple times here and there in places where I don't mind overriding String.prototype. As a static function, you can use:
tmpl.js:
function tmpl(tmpl, o) {
return tmpl.replace(/<%=(?:"([^"]*)"|(.*?))%>/g, function (item, qparam, param) {
return o[qparam] || o[param];
});
}
An example template:
<div id="bar"></div>
<script type="text/x-tmpl" id="foo">
<h1><%=title%></h1>
<p><%=body%></p>
</script>
<script>
(function () {
var foo,
bar;
foo = document.getElementById('foo');
bar = document.getElementById('bar');
bar.innerHTML = tmpl(foo.innerHTML, {
title: 'foo bar baz',
body: 'lorem ipsum dolor sit amet'
});
}());
</script>
The base tmpl script can of course be modified to take advantage of document fragments to actually build out DOM elements, but as-is I'm not sure whether it counts as a "template library".
The best solution to this problem is to pre-compile your templates before you deploy your extension. Both handlebarsjs and eco offer pre-compilation as a feature. I actually wrote a blog post that goes into more depth.
Maybe you can write a function eval1:
function eval1(blah) {
var s = document.createElement("script");
s.src = blah;
document.head.appendChild(s);
document.head.removeChild(s);
}
and do a find/replace in the library you want, but that'd be cheating, right?
I recently run into the same problem. After updating manifest version my extension stopped working. I tried Mustache but it unable to render index of the array and names of the object properties. So I had to create my own simple but effective templating library Ashe which is free of eval and new Function. Hope it will help someone.
https://developer.chrome.com/extensions/sandboxingEval
Not sure when it was added, but you can do Firefox style sandboxing in Chrome now. I'm porting my Firefox extension, so I need this (since I don't have evalInSandbox :P)
What is the best way to manage the JavaScript files and the functions/objects context in an ASP.NET MVC app?
Google says http://javascriptmvc.com/
If you're looking for something like that, you should definitely check out MooTools as they implement classes almost exactly the way you describe. Overall, I've found their approach to be very clean, extensible, and maintainable. For example, here is a class template I use to write all of my classes (note that it uses some MooTools-specific syntax):
var className = new Class ({
Implements: [Events, Options],
options: {
option1: 'option1',
option2: 'option2'
},
initialize: function(options){
this.setOptions(options);
},
function1: function(){
},
function2: function(){
}
});
I put all my js files in the Content/Js folder. Then add URL helpers that allow me to change this in the future. My code isn't online, but I stole the idea from Rob Conery MVC Commerce demo.
Not sure what you mean by "manage...the functions/objects context in ASp.NET MVC app"
I think you're asking how to segment/partition your scripts.
You should separate your JS files into separate chunks of functionality.
yes , but this is not a MooTools unique technique,
this is called Object literal pattern.
i'm looking for a way to manage my ajax app according to the current state od the asp.net mvc
i'm thinking about a main js file that
is responsible for all the calls of js function like:
mainApp = function(){
return {
init: function(){
},
function1: function(){
}
};
};
nut in a way of it fits an mvc app.