I’m new at Backbone.js.And I hava some problem at this keyworks.I hava a Backbone view blow:
var print = Backbone.View.extend({
el : $('ul li.newItem'),
events : { 'click li.newItem':'printText'},
initialize:function(){
_.bind(printText,this); // does 'this' refer to the li.newItem ?
alert(1233); // init does't work.
},
printText : function(){
//I wanna print the hello world text each list item when clicked.
}
});
var print = new print();
Here is my demo : http://jsbin.com/evoqef/3/edit
You have two problems that are keeping your
initializefrom working:printTextin scope._.bindand_.bindAllbehave differently.The first is easy to fix, you want to use
this.printText, not justprintText._.bindbinds a single function to athisand returns that bound function;_.bindAll, on the other hand, binds several named functions to athisand leaves the bound functions attached to the specifiedthis. So, doing this:doesn’t do anything useful as you’re throwing away the bound function. You’d want to do this:
Or more commonly in Backbone apps, you’d use
_.bindAll:Now you have a functioning
initializeand you’ll have the rightthisinsideprintTextand we can move on to fixingprintText. I think you want to extract the text from the<li>that was clicked; you can do this like this:But that still doesn’t work and we’re left to wondering what’s going on here. Well, Backbone binds events to a view’s
elso let us have a look at that:When that
Backbone.View.extendruns, there won’t be anyli.newItemelements in the DOM so you won’t get a usefulelin that view. The usual approach here would be to have a view that looks like this:We set
tagNameto'li'and let Backbone create the<li>by itself. Then we’d pass the counter value to thePrintview as an argument, Backbone will take care of leaving the argument inthis.options.iwhen we saynew Print({ i: ... }).Now we just have to adjust the
addItemmethod in yourListViewto create newPrints and add them to the<ul>:Updated demo: http://jsbin.com/evoqef/10/edit
I’ve also made a few other changes:
this.$elinstead of$(this.el), there’s no need to create something that’s already available.this.$()instead of$('ul', this.el), same result butthis.$()doesn’t hide the context at the end of the$()function call andthis.$()is more idiomatic in Backbone.