[英]How to pass back model attribute from a view Backbone
I have a controller: 我有一个控制器:
var layout = new LayoutView();
App.holder1.show(layout);
var my_view = new myView({id: options})
layout.holder1.show();
console.log(my_view.model.get('name')) <---- I want this
I want to get my_view.model.get('name')
however, the issue is I get undefined
. 我想
get my_view.model.get('name')
但是问题是我undefined
。 I have console.log
the model and it is populated ok, however I think it's because it's not fully loaded yet when I try the get. 我有
console.log
模型,它已填充好,但是我认为这是因为当我尝试获取时它尚未完全加载。
This is my current thisView: 这是我当前的thisView:
var thisView = Backbone.Marionette.ItemView.extend({
initialize: function (options) {
this.model.fetch();
},
model: new myModel(),
template: testExampleTemplate,
});
return thisView;
You'll have the object populated only after the success callback function: 仅在成功回调函数之后,才会填充对象:
initialize: function (options) {
this.model.fetch({
success: function(model){
console.log(model.get('name'));
};
});
}
Listen for an event. 听一个事件。 "change" or "reset" will work.
“更改”或“重置”将起作用。
viewInstance.model.on("change", function(){
viewInstance.model.get("nameOfAttribute");
// do something
});
http://backbonejs.org/#Events-catalog http://backbonejs.org/#Events-catalog
There's a few ways to approach this. 有几种方法可以解决此问题。 First, you could listen for a change event from the model in the view, and do whatever it is you need when the change event fires.
首先,您可以从视图中的模型中监听更改事件,并在更改事件触发时执行所需的任何操作。 If you need to do something no matter what, you have a couple of options: you could write an implementation for you model's parse method that fires an event your view listens for and does something in response, or you can do something in the success callback for the fetch method itself (passed as an option to fetch).
如果您无论如何都需要做一些事情,则有两种选择:您可以为模型的parse方法编写一个实现,该实现会触发视图监听的事件并做出响应以响应事件,或者您可以在成功回调中做一些事情用于获取方法本身(作为获取的选项传递)。 I can provide an example if I understand better which approach makes sense for your situation.
如果可以更好地理解哪种方法适合您的情况,我可以举个例子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.