I guess that's the simple question. I'm new in js
, especially in Backbone.js
.
All I want to know is how I can refer to my function inside jquery function.
getLanguages: function() {
...
return languages;
},
render: function() {
...
$("input[type='checkbox']").bind("change", function() {
// todo: getLanguages
});
}
I tried to get languages via this
but, of course, I got checkbox
in this case.
Edit: It's so simple. Many thanks to all!!!
This is a classic problem in Javascript. You need to reference this
inside a callback, but this
changes to the element being bound to. A cheap way to do it:
render: function() {
var that = this;
$("input[type='checkbox']").bind("change", function() {
that.getLanguages();
});
}
that
will stay defined as the this
that render
is defined on.
However, you’re using Backbone, and it has more suitable ways to handle this situation. I don’t know the name of your Backbone.View
class, but here’s an example adapted from the documentation:
var DocumentView = Backbone.View.extend({
events: {
"change input[type='checkbox']": "doSomething"
},
doSomething: function() {
this.getLanguages(); # uses the correct this
}
});
Calling bind
inside render
is not The Backbone Way. Backbone views are made to handle event delegation without the unfortunate need to pass this
around.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments