質問

数日前にbackbone.jsを見つけましたが、JavaScriptのスキルはあまり良くありませんが、JavaScript開発のためのきれいなコードツールであることがわかりました。ただし、ドキュメントを読んだ後、簡単な連絡先アプリをコーディングすることにしました。ブラウザLocalStorageの連絡先データを保存します。これは私の連絡先アプリのコード//ソースコードです

$(function() {


    //Contact Model
    Contact = Backbone.Model.extend({
        //Contact Defaults
        defaults : {
            first_name : 'First Name',
            last_name : 'Last Name',
            phone : 'Phone Number'
        },
        //Constructor(intialize)
        //Ensuring each contact has a first_name,last_name,phone
        intialize: function(){
            if(!this.get("first_name")) {
                this.set({"first_name":this.defaults.first_name});
            }
            if(!this.get("last_name")) {
                this.set({"last_name":this.defaults.last_name});
            }
            if(!this.get("phone")) {
                this.set({"phone":this.defaults.phone});
            }
        }
    });

    //Contact Collection

    //The collection is backed by localstorage
    ContactList = Backbone.Collection.extend({
        //Model
        model : Contact,
        //Save all contacts in localstorage under the namespace of "contacts"
        localStorage: new Store("contacts")
    });

    //Create global collection of Contacts
    Contacts = new ContactList;

    //Contact View
    ContactView = Backbone.View.extend({
        tagName : "li",

        template: _.template($("#item_template").html()),

        events : {
            "click span.contact-delete": "delete_contact"
        },
        intialize: function(){
            this.bind('change',this.render,this);
            this.bind('destroy',this.remove,this);
        },
        render: function() {
          $(this.el).html(this.template(this.model.toJSON()));
          this.setContent();
          return this;
        },
        setContent: function() {
            var first_name = this.model.get("first_name");
            var last_name = this.model.get("last_name");
            var phone = this.model.get("phone");
            var name = first_name+" "+last_name;
            this.$('.contact-name').html(name);
            this.$('.contact-phone').html(phone);
        },
        remove: function() {
              $(this.el).remove();
        },
        delete_contact: function() {
            this.model.destroy();
        }
    });

    //The Application
    AppView = Backbone.View.extend({

        el: $("#contact-app"),

        events : {
            "click #new-contact #save-button": "createContact"
        },
        intialize: function() {

            Contacts.bind("add", this.addOne, this);
            Contacts.bind("reset", this.addAll, this);          
            Contacts.fetch();
        },

        // Add a single contact item to the list by creating a view for it, and
        // appending its element to the `<ul>`.
        addOne: function(contact) {
          var view = new ContactView({model: contact});
          this.$("#contact-list").append(view.render().el);
        },
        // Add all items in the **Contacts** collection at once.
        addAll: function() {
          Contacts.each(this.addOne);
        },
        // Generate the attributes for a new Contact item.
        newAttributes: function() {
          return {
            first_name : this.$('#first_name').val(),
            last_name : this.$('#last_name').val(),
            phone : this.$('#phone').val()
          };
        },
        createContact: function() {
            Contacts.create(this.newAttributes());
            //Reset Form
            this.$('#first_name').val('');
            this.$('#last_name').val('');
            this.$('#phone').val('');
        }
    });

    // Finally,kick things off by creating the **App**.
     var App = new AppView;
});

これが私のHTMLソースです

   <div id="contact-app">

        <div class="title">
            <h1>Contacts App</h1>
        </div>

        <div class="content">

            <div id="new-contact">
                <input name="first_name" placeholder="First Name" type="text" id="first_name"/>
                <input name="last_name" placeholder="Last Name" type="text" id="last_name" />
                <input name="phone" placeholder="Phone Number" type="text" id="phone" />
                <button id="save-button">Create Contact</button>
            </div>

            <div id="contacts">
                <ul id="contact-list">
                </ul>
            </div>

            <div id="contact-stats"></div>

        </div>

    </div>
    <script type="text/template" id="item_template">
    <div class="contact">
        <div class="contact-name"></div>
        <div class="contact-phone"><div>
        <span class="contact-delete"></span>
    </div>
  </script>

連絡先データはローカルストレージに保存されますが、これはFireBugで確認できますが、ビューは更新されません。 Backbone.jsは初めてです。問題は、JavaScriptエラーはありません。

役に立ちましたか?

解決

コレクションにモデルを追加するために「作成」の代わりに「追加」を使用してみてください(「Create」メソッドによって「追加」イベントが起動されているとは思いません)。

それ以外の

    Contacts.create(this.newAttributes());

使用する

   Contacts.add(this.newAttributes());

モデルをローカルストレージに保存するには、保存方法を呼び出すことができます

addOne: function(contact) {

      var view = new ContactView({model: contact});
      contact.save();
      this.$("#contact-list").append(view.render().el);
    }, 

編集:

別のことは、あなたの「intialize」メソッドのスペルをチェックしてください。「初期化」であるべきだと思います。

これが次のとおりです jsfiddle, 、私はそれをJSFiddleのLocalStorageに保存していませんが、それはあなたによって機能するはずです。

他のヒント

モデルでは、 defaults デフォルト値の世話をする必要があります initialize 機能はおそらく必要ありません。私が間違っている場合、誰かがこれについて私を修正します。

あなたの連絡先で、あなたはあなたのレンダリングラインをこれに変更する必要があるかもしれません initialize 方法:

this.model.bind('change', _.bind(this.render, this));
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top