[英]Backbone.View cannot call a function
我正在嘗試調用一個函數,但出現錯誤,說明函數未定義。
window.PackageView = Backbone.View.extend({
tagName: "div",
className: "package-template",
events:{
"click #display-name" : "getNodeId",
},
initialize: function() {
_.bindAll(this,'render', 'getNodeId', 'getAction');
this.template = _.template($('#package-template').html());
$(this.el).html(this.template); //Load the compiled HTML into the Backbone "el"
nodeInstance.bind('reset', this.render, this);
},
render: function() {
//.. no need to worry about this.
},
getNodeId: function(){
objectJSON = jAccess.getJSON(); // I get the JSON successfully
nodeIdArray = []
_.each(objectJSON, function(action){
_.each(action.Nodes, function(action){
nodeIdArray.push(action.Id);
this.getAction(); // Here is the problem. I get an error
});
});
},
getAction: function(){
actionsArray = [];
objectJSON = jAccess.getJSON();
_.each(objectJSON, function(action){
_.each(action.Nodes, function(action){
if(action.Id == 5) {
_.each(action.Actions, function(action){
actionsArray.push(action.Name);
});
}
});
});
console.log(actionsArray);
}
});
我不知道我要去哪里錯了。 幫幫我。
我收到一條錯誤消息,指出“未定義”不是函數求值('this.getAction()')
作為一個簡單的解決方法,您應該能夠:
getNodeId: function(){
var self = this;
objectJSON = jAccess.getJSON();
nodeIdArray = []
_.each(objectJSON, function(action){
_.each(action.Nodes, function(action){
nodeIdArray.push(action.Id);
self.getAction();
});
});
},
我認為使用下划線綁定功能可能會有更優雅的解決方案,我將進行檢查。
編輯僅當在RESTful資源的集合上使用each方法時,才可以使用更優雅的解決方案,因此在這種情況下不適用。 例如,如果您有一組消息,則可以執行以下操作來保留上下文。
addAllMessages: function(messages) {
messages.each(this.addMessage, this);
},
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.