创建新的 Backbone 视图时如何知道元素是否已经在 DOM 中 [英] How to know if element is already in the DOM when creating new Backbone view

查看:16
本文介绍了创建新的 Backbone 视图时如何知道元素是否已经在 DOM 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

情况如下:页面第一次打开时,已经由服务器(php)准备好DOM.

here's the situation: When page is opened for the first time, it already has prepared DOM by server(php).

如果用户打开了 javascript,那么我想将我的页面转换为 Web 应用程序(或您称之为的任何内容).一旦 Javascript 被初始化,Backbone 从服务器获取集合.问题是,其中一些获取的项目已经在页面上.

If user has javascript turned on, then i want to convert my page to web app(or whatever you call it). As soon as Javascript is initialized, Backbone fetches collection from server. The problem is, that some of these fetched items are already on page.

现在我如何标记那些已经在 DOM 中的项目?我如何将它们与 Backbone 视图联系起来?

Now how can i mark those items which already are in the DOM? And how can i tie them up with the Backbone view?

推荐答案

将 Backbone.View 连接到现有的 DOM 元素很简单:

Hooking up a Backbone.View to an existing DOM element is simple:

//get a referent to the view element
var $el = $("#foo");

//initialize new view
var view = new FooView({el:$el});

视图现在处理 #foo 元素的事件,以及所有其他视图优点.你不应该调用 view.render.如果这样做,它会将视图重新渲染到元素.这意味着您不能在 render 方法中定义任何必要的代码.

The view now handles the #foo element's events, and all the other View goodness. You shouldn't call view.render. If you do, it will re-render the view to the element. This means that you can't define any necessary code in the render method.

至于如何找出哪些元素已经在 DOM 中,以及如何为每个视图找到相应的元素 - 如果不知道您的数据和 html 究竟是什么样子,回答起来会有点复杂.作为一般建议,请考虑使用 data-* 属性来匹配元素.

As to how to find out which elements are already in the DOM, and how to find the corresponding element for each view - that's a bit more complicated to answer without knowing exactly how your data and html looks like. As a general advice, consider using data-* attributes to match up the elements.

假设您有一个 DOM 树:

Let's say you have a DOM tree:

<ul id="list">
  <li data-id="1">...</li>
  <li data-id="2">...</li>
  <li data-id="5">...</li>
</ul>

您可以像这样将模型绑定/渲染到容器:

You could bind/render a model to the container like so:

var view;

//container element
var $list = $("ul#list");

//find item node by "data-id" attribute
var $item = $list.find("li[data-id='" + model.id+ "']");

if($item.length) {
  //element was in the DOM, so bind to it
  view = new View( {el:$item, model:model} );
} else {
  //not in DOM, so create it
  view = new View( {model:model} ).render();
  $list.append(view.el);
}

这篇关于创建新的 Backbone 视图时如何知道元素是否已经在 DOM 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆