我按照本书https://leanpub.com/marionette-gentle-introduction中的示例进行操作。我的问题是,当我通过单击按钮更改模型时,视图不会重新渲染。作为question的答案,我不需要做任何事情,因为Backbone / MarionetteJS足够聪明,可以改变观点。 这是代码
<!DOCTYPE html>
<html lang="en">
<head>
<title>Demo marionettejs</title>
<script src="./vendors/jquery/dist/jquery.js" type="text/javascript"></script>
<script src="./vendors/underscore/underscore.js" type="text/javascript"></script>
<script src="./vendors/backbone/backbone.js" type="text/javascript"></script>
<script src="./vendors/backbone.marionette/lib/backbone.marionette.js" type="text/javascript"></script>
</head>
<body>
<div id="main-region" class="container">
<p>Here is static content in the web page. You'll notice that it gets
replaced by our app as soon as we start it.</p>
</div>
<script type="text/template" id="contact-template">
<p><%- firstName %> <%- lastName %> : <%- time %> </p> <br />
<button>Change model</button>
</script>
<script type="text/javascript">
var ContactManager = new Marionette.Application();
ContactManager.Contact = Backbone.Model.extend({});
ContactManager.ContactView = Marionette.ItemView.extend({
template: "#contact-template",
initialize: function () {
this.currentMeterId = null;
},
events: {
"click button": "changeModel"
},
modelEvents: {
"change": "modelChanged"
},
changeModel: function() {
this.model.set("time", (new Date()).toString());
},
modelChanged: function() {
console.log("Model changed : " + this.model.get('time'));
},
//EDIT
onRender: function() {
//Create jsTree here.
}
});
ContactManager.on("before:start", function () {
var RegionContainer = Marionette.LayoutView.extend({
el: "#app-container",
regions: {
main: "#main-region"
}
});
ContactManager.regions = new RegionContainer();
});
ContactManager.on("start", function () {
var alice = new ContactManager.Contact({
firstName: "Alice",
lastName: "Arten",
time: "#"
});
var aliceView = new ContactManager.ContactView({
model: alice
});
ContactManager.regions.main.show(aliceView);
});
ContactManager.start();
</script>
</body>
</html>
@Edit 这段代码只是样本。在我的真实应用程序中,我有一个ajax任务,可以在视图中更改DOM。这个ajax任务在onRender事件中创建了一个树(jsTree)。如果我使用modelEvents:{&#34;更改&#34;:&#34;渲染&#34;},我的jsTree将重新加载并失去其状态。所以我只想更新视图中的模型值,其他DOM保留。
答案 0 :(得分:0)
您指向的accepted answer question指向another question,其中包含以下内容:
modelEvents: {
'change': "modelChanged"
},
modelChanged: function() {
console.log(this.model);
this.render();
}
most upvoted answer建议相同:
modelEvents: {
'change': 'fieldsChanged'
},
fieldsChanged: function() {
this.render();
}
对最受欢迎的答案的评论建议
只是
{'change': 'render'}
也可以做到这一点
这意味着你可以做到
modelEvents: {
'change': 'render'
}
所以你不得不告诉牵牛花在模型变化时调用渲染。
我不认为骨干和木偶夫妇足够聪明,知道你是否需要渲染模型变化的视图,或者除非你告诉他们你不想要;)