Backbone.js - 从现有 html 实例化模型/视图

发布于 2024-11-25 13:08:24 字数 1368 浏览 2 评论 0原文

我今天开始研究backbone.js,作为更好地组织应用程序中代码的一种方法。

我想知道(概念上 - 所以无论如何用伪代码回复)我将如何使用我的现有 html 来创建主干模型(和视图)。

我发现的所有教程都包括使用空白 html 模板,然后使用 ajax 注入内容。我不想这样做。

假如我有一本藏书。

<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title>My Book Collection</title>
</head>
<body>
    <head>

    </head>
    <body>
        <ul id="bookCollection">
            <li class="book" data-book-id="1"><input type="text" name="book_1_name" value="My Book A"/></li>
            <li class="book" data-book-id="2"><input type="text" name="book_2_name" value="My Book B"/></li>
            <li class="book" data-book-id="3"><input type="text" name="book_3_name" value="My Book C"/></li>
            <li class="book" data-book-id="4"><input type="text" name="book_4_name" value="My Book D"/></li>
            <li class="book" data-book-id="5"><input type="text" name="book_5_name" value="My Book E"/></li>
        </ul>
    </body>
</body>
</html>

在这个阶段,我想开始将每本书作为一个模型进行管理,每当书名发生更改时调用一个函数(只是函数中的一个警报以进行概念验证),然后调用一个 URL 将模型的更改与我的数据库同步。

任何人都可以为我指出正确的方向,以找到使用页面上现有的 html 执行上述操作的方法吗?

如果它有所作为,我计划使用小胡子作为我的模板。

I've started looking at backbone.js today as a way to better organize the code in my application.

I was wondering (conceptually - so reply with pseudocode by all means) how I would use my existing html to create Backbone Models (and Views).

All of the tutorials I've found consist of using a blank html template and then injecting in the content using ajax. I don't want to do this.

If I have a collection of books.

<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title>My Book Collection</title>
</head>
<body>
    <head>

    </head>
    <body>
        <ul id="bookCollection">
            <li class="book" data-book-id="1"><input type="text" name="book_1_name" value="My Book A"/></li>
            <li class="book" data-book-id="2"><input type="text" name="book_2_name" value="My Book B"/></li>
            <li class="book" data-book-id="3"><input type="text" name="book_3_name" value="My Book C"/></li>
            <li class="book" data-book-id="4"><input type="text" name="book_4_name" value="My Book D"/></li>
            <li class="book" data-book-id="5"><input type="text" name="book_5_name" value="My Book E"/></li>
        </ul>
    </body>
</body>
</html>

At this stage I would like to start managing each book as a model, calling a function whenever book names are changed (just an alert in the function for proof of concept), and then calling a URL to sync changes to the model with my database.

Can anyone point me in the right direction for a way to do the above using existing html on a page?

If it makes a difference I plan on using mustache for my templating.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

∞梦里开花 2024-12-02 13:08:24

我真的也想做同样的事情,只是找到了解决办法!

试图构建一个待办事项列表示例,其中页面上已经有一些待办事项,希望将它们作为模型放入我的待办事项集合中,并以与添加到空白页面的元素相同的方式管理它们。

整个 js 代码作为要点粘贴在 https://gist.github.com/1255736 中,并带有注释以解释更多信息。

重要的部分是如何实例化集合。基本上:

  1. 您通过 jQuery 获取现有的 html 元素。如果您的模型的视图基于 tagName:“li”,那么这就是您需要在此处检索的标记类型。
  2. 您迭代这些标记以抓取其中构成模型的数据并创建模型。
  3. 您为每个模型创建一个视图,并向其传递模型和基本元素。这就是我遇到的问题:我正在创建视图,然后才尝试稍后通过 my_view.el = xxx 添加它。这是行不通的。
  4. 将模型添加到集合中

注意:集合通常会稍后绑定到视图,以便使用 collection.add 也会更新视图。由于在构造函数中调用了初始化,因此集合尚未绑定,并且您不会通过在此处添加元素来重复 HTML 中的元素。

// this is the important part for initializing from html!
khepin.Todos = Backbone.Collection.extend({
    model: khepin.Todo,

    // In this function we populate the list with existing html elements
    initialize: function() {
        _.each(
            // get all the <li></li> todo items (the base for the todo view)
            // and for each of them:
            $('.todo'),
            function(a){
                // Create the model
                var todo = new khepin.Todo();
                // Find the todo's text
                var task = $(a).find('span')[0];
                task = $(task).text();
                // set the model correctly
                todo.set({
                    task: task
                });
                // create the todo view
                var todoView = new khepin.TodoView({
                    model: todo,
                    el: a // the el has to be set here. I first tried calling new TodoView and setting the 'el' afterwards
                    // and the view wasn't managed properly. We set the "el' to be the <li></li> we got from jQuery
            });
        // Add this new model to the collection
        this.add(todo);
        },
        this
    );
}
})

希望这有帮助!

I was really trying to do the same thing as well and just found my way around it!

Was trying to build on a todo list example where I'd already have some todos on the page, want to bring them as models in my Todos collection and have them managed the same way it happens for elements that were added to a blank page.

The whole js code is pasted as a gist there https://gist.github.com/1255736 with comments to explain more.

The important part is on how to instantiate the collection. Basically:

  1. you get your existing html elements through jQuery. If your model's view is based on a tagName: 'li', then this is the kind of tag you need to retrieve here.
  2. You iterate through these tags to scrape the data that's in there that constitutes your models and create your models
  3. You create a view for each model, passing it the model and the base element. This was the problem I had: I was creating the view and only then trying to add it later through my_view.el = xxx. This doesn't work.
  4. You add your model to the collection

Note: the collection is usually tied to a view later so that using collection.add will update the view as well. Since initialize is called in the constructor, the collection has not been bound yet and you won't duplicate elements in your HTML by adding them here.

// this is the important part for initializing from html!
khepin.Todos = Backbone.Collection.extend({
    model: khepin.Todo,

    // In this function we populate the list with existing html elements
    initialize: function() {
        _.each(
            // get all the <li></li> todo items (the base for the todo view)
            // and for each of them:
            $('.todo'),
            function(a){
                // Create the model
                var todo = new khepin.Todo();
                // Find the todo's text
                var task = $(a).find('span')[0];
                task = $(task).text();
                // set the model correctly
                todo.set({
                    task: task
                });
                // create the todo view
                var todoView = new khepin.TodoView({
                    model: todo,
                    el: a // the el has to be set here. I first tried calling new TodoView and setting the 'el' afterwards
                    // and the view wasn't managed properly. We set the "el' to be the <li></li> we got from jQuery
            });
        // Add this new model to the collection
        this.add(todo);
        },
        this
    );
}
})

Hope this helps!

阳光下的泡沫是彩色的 2024-12-02 13:08:24

Backbone 的视图始终绑定到特定的 html 元素(视图的属性 el)。您可以将 BookCollectionView 绑定到 ul#bookCollection 并将 BookView 绑定到 li.book,这应该适合您当前的模板结构。

您可以使用模型的 url 将 Book 模型映射到视图。如果从该 url 获取模型,并且您已为模型更改定义了事件绑定,则相应的视图应使用新模型数据刷新。这同样适用于馆藏的网址和书籍收藏。

我猜关于主干的好的教程并不多,但是可以学习一些类似的东西 http://liquidmedia.ca/blog/2011/02/backbone-js-part-3/http://www.jamesyu.org/ 2011/02/09/backbone.js-tutorial-with-rails-part-2/。如果你能提出一些更具体的问题,我猜会更容易!

Backbone's views are always bound to a specfic html element (the view's attribute el). You could have something like a BookCollectionView bound to ul#bookCollection and a BookView bound to li.book, which should be fine with your current template structure.

You can map a Book model to a view using a url to the model. If the model is fetched from that url and you have defined an event binding for the model change, the according view should refresh with the new model data. Same applies for the collection's url and a collection of books.

There are not many good tutorials on backbone out i guess, but study something like http://liquidmedia.ca/blog/2011/02/backbone-js-part-3/ or http://www.jamesyu.org/2011/02/09/backbone.js-tutorial-with-rails-part-2/. Guess it is easier if you can come up with some more concrete questions!

空城之時有危險 2024-12-02 13:08:24

我遇到了同样的问题,并在我的主视图(ul 列表)的构造函数中以这种方式解决了它 - 从骨干 0.9 开始。

我在脑海中从coffeescript语法转换了它,所以如果有一些语法错误,请保持温和。

myListView = Backbone.View.extend({
    initialize: function() {
        ._each(this.$el.children(), function(book, i) {
             new Backbone.View({
                  el: book,
                  model: this.collection.at(i)
             });
        });
    }
});

并像这样调用它:

new myListView({
     collection: anExistingCollection,
     el: $('#bookCollection')
});

重要的是,集合“anExistingCollection”的顺序与您已经存在的顺序相同生成的列表条目,因为本示例依赖于相同的索引。

(未经测试)

I had the same problem and solved it this way within the constructor of my main view (the ul list) - as of backbone 0.9.

I converted it in my mind from coffeescript syntax so please be gentle if there are some syntax errors.

myListView = Backbone.View.extend({
    initialize: function() {
        ._each(this.$el.children(), function(book, i) {
             new Backbone.View({
                  el: book,
                  model: this.collection.at(i)
             });
        });
    }
});

and calling it like this:

new myListView({
     collection: anExistingCollection,
     el: $('#bookCollection')
});

It's important that the order of the collection 'anExistingCollection' is the same as your already generated list entries as this example relies on the same index.

(untested)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文