使用Ember.js构建搜索框搜索

Gio*_*tta 4 javascript ember.js ember-data

我想在我的Notes.Application中构建一个简单的搜索框来搜索我的笔记.我正在寻找这个网站,Ember表格和谷歌,并没有那么多的解决方案.我发现只有两个,他们不适合我的应用程序皱眉.问题是我不知道如何做到这一点.

这是我的应用程序:

<script type="text/x-handlebars" data-template-name="index">  
    <div class="wrap">
      <div class="bar">
      {{input type="text" class="search" placeholder="Where is my bookmark??" value=search action="query"}}

        <div class="bar-buttons">
          <button {{action "addNote"}}> NEW </button>
          <button> HOME </button>
        </div>
      </div>
      <aside>
        <h4 class="all-notes">All Notes {{length}}</h4>
          {{#each item in model}}
            <li>
              {{#link-to 'note' item}} {{item.title}} {{/link-to}}
            </li>
          {{/each}}
      </aside>
      {{outlet}}
    </div> 
</script>
Run Code Online (Sandbox Code Playgroud)

控制器:

Notes.IndexController = Ember.ArrayController.extend ({
search: '',

actions:{
    query: function() {
      // the current value of the text field
      var query = this.get('search');
    },

    addNote: function () {
        this.transitionToRoute('main');
    }
}
});
Run Code Online (Sandbox Code Playgroud)

模型:

    Notes.Note = DS.Model.extend ({
    title: DS.attr('string'),
    body: DS.attr('string'),
    url: DS.attr('string')
    });

    Notes.Note.FIXTURES = [ 
    { 
    id: 1, 
    title:'hello world', 
    body: 'ciao ciao ciao ciao', 
    url: '' 
    }, 
    { 
    id: 2, 
    title: 'javascript frameworks',
    body: 'Backbone.js, Ember.js, Knockout.js', 
    url: '...'
    },
    {
     id: 3,
     title: 'Find a job in Berlin',
     body: 'Monster, beralinstartupjobs.com',
     url: '...'
    }
    ];
Run Code Online (Sandbox Code Playgroud)

但无论如何,这仍然是硬编码数据,后来将只是用户动态添加的注释.

任何建议都非常感谢.

Mar*_*ior 8

你可以这样做覆盖以下arrangedContent属性IndexController:

Notes.IndexController = Ember.ArrayController.extend ({
    search: '',    
    titleFilter: null,
    actions:{
        query: function() {
            // the current value of the text field
            var query = this.get('search');
            this.set('titleFilter', query);
        },
        addNote: function () {
            this.transitionToRoute('main');
        }
    },
    arrangedContent: function() {
        var search = this.get('search');
        if (!search) { return this.get('content') }

        return this.get('content').filter(function(note) {            
            return note.get('title').indexOf(search) != -1;
        })
    }.property('content', 'titleFilter')
});
Run Code Online (Sandbox Code Playgroud)

并在您的模板中使用 {{#each item in arrangedContent}}

在行动中查看此内容http://jsfiddle.net/marciojunior/v966z/

  • `content`是所有加载数据的地方,所以我们不能直接更改它,因为我们可以在过滤时丢失数据.因此`ArrayController`提供了一个`arrangeContent`属性,我们可以在其中安排内容,如分页,排序,过滤等.因为你只想在用户按输入字段中的Enter键时过滤数据,arrangeContent观察内容和titleFilter,因此,当触发查询操作时,我们设置titleFilter属性,这将更改arrangeContent,并且因为模板正在观察它,所以更新是自动的. (4认同)