gpt4 book ai didi

javascript - 将数据绑定(bind)到 DOM 的示例

转载 作者:数据小太阳 更新时间:2023-10-29 05:36:37 26 4
gpt4 key购买 nike

我在 Backbone.js 中阅读了以下内容' 页面:

When working on a web application that involves a lot of JavaScript, one of the first things you learn is to stop tying your data to the DOM. It's all too easy to create JavaScript applications that end up as tangled piles of jQuery selectors and callbacks, all trying frantically to keep data in sync between the HTML UI, your JavaScript logic, and the database on your server. For rich client-side applications, a more structured approach is often helpful.

我不确定我是否完全理解上面这段话(我也不确定我是否完全理解使用Backbone.js的必要性)。

谁能给我一个将数据绑定(bind)到 DOM 的示例以及 Backbone.js 如何解决它?

编辑:

这是一个例子吗?

jQuery(document).ready(function($) {
// Header
jQuery('#header #searchbox').attr('placeholder', '<?php echo pll__("Header Search Field"); ?>');

(etc...)

(这是我使用的 hack,因为我不知道如何使用 php 来实现)。

因此,如果我修改#searchbox 的ID 或移动它的位置,代码将不再有效。上面这段话是指这个吗?

最佳答案

我刚刚使用显示模态编辑框的 backbone 做了一些事情,您可以在其中编辑项目的名称。因为这个名字也显示在主页上,所以我想同时更新它。但我不想识别 DOM 元素并直接用我的编辑结果更新它。相反,我创建了一个 Backbone 模型:

this.newModel = new app.Project({model: this.model});

然后我监听新模型的任何更改,在本例中为 project_name 属性:

this.listenTo(this.newModel, 'change:project_name', this.updateName);

然后我使用“newModel”创建一个新 View

modal = new app.ProjectModal({
model: this.newModel,
});

然后显示,如果名称在模态视图中发生变化,则在“父” View 中触发“this.updateName”函数,因此无需识别实际 DOM 元素的位置。

整个“父”函数如下所示:

    app.ProjectCardView = Backbone.View.extend({

tagName: 'article',
className: 'project',

template: _.template( $("#tpl-project-card-summary").html() ),

events: {
'click .settings-btn': 'showProjectModal'
},

initialize: function() {

//a slightly different model is used to populate project than this card...
this.newModel = new app.Project({model: this.model});
return this;
},

render: function() {

this.$el.html( this.template(this.model.toJSON()) );
return this;
},

showProjectModal: function (e) {

this.listenTo(this.newModel, 'change:project_name', this.updateName);

this.modal = new app.ProjectModal({
model: this.newModel
});
return this;

},

updateName: function() {

if (this.modal) {
this.$el.find('.item_name').text(this.model.get("project_name"));
}

return this;
}

});

显然我必须在某处更新 DOM,但现在它与编辑分离并且更易于管理。

关于javascript - 将数据绑定(bind)到 DOM 的示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13136665/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com