Javascript 使用Ember中的文本框对模型进行实时排序或筛选

Javascript 使用Ember中的文本框对模型进行实时排序或筛选,javascript,ember.js,filtering,Javascript,Ember.js,Filtering,我在看《灰烬》的视频,无意中发现了自动完成小部件。我试图实现类似的东西,但它似乎不起作用 我使用$.getJSON获取数据,并希望使用textbox对其进行过滤 这是我试过的 App = Ember.Application.create(); App.Model = Ember.Object.extend({ }); App.IndexRoute = Ember.Route.extend({ redirect : function() { this.transiti

我在看《灰烬》的视频,无意中发现了自动完成小部件。我试图实现类似的东西,但它似乎不起作用

我使用$.getJSON获取数据,并希望使用textbox对其进行过滤

这是我试过的

App = Ember.Application.create();

App.Model = Ember.Object.extend({

});

App.IndexRoute = Ember.Route.extend({
    redirect : function() {
        this.transitionTo('users');
    }
});

App.UsersController = Ember.ArrayController.extend({

    filteredContent : function() {
        var searchText = this.get('searchText'), regex = new RegExp(searchText, 'i');

        return this.get('model').filter(function(item) {
            return regex.test(item.name);
        });
    }.property('searchText', 'model')
});

App.Users = App.Model.extend({
    id : "",
    name : ""
});

App.UsersRoute = Ember.Route.extend({
    model : function() {
        return App.Users.findAll();
    },
    setupController : function(controller, model) {
        controller.set('model', model);
    }
});


App.Users.reopenClass({
    findAll : function() {
        return $.getJSON("user.php", function(data) {
            return data.map(function(row) {
                return App.Users.create(row);
            });
        });
    }
});

App.Router.map(function() {
    this.resource("users", {
        path : "/users"
    });
});
这是我的HTML

       <body>
        <script type="text/x-handlebars" data-template-name="users">

            {{view Ember.TextField value=searchText}}
            <button {{action last}}>filter</button>
            <button {{action refresh}}>refresh</button>

             {{#each item in content }}
             <tr><td>
             <p> {{item.name}}</p>
             </td></tr>
            {{/each}}
        </script>

        <script type="text/x-handlebars">
            <h1>Application Template</h1>
            {{outlet}}
        </script>

    </body>

你知道我为什么会得到这个吗?

我想你是在$getJSON的承诺兑现之前回来的。尝试更改您的App.User.findAll,以便它从成功回调中返回结果。因此,具体而言,您的findAll实现可能如下所示:

App.Users.reopenClass({
  findAll: function() {
    return $.getJSON("https://api.github.com/users/rjackson/repos", function(data) {
      return data.map(function(row) { return App.Users.create(row); });
    });
  }
});
另外,我认为您不需要手动创建ArrayProxy对象。从routes模型钩子返回一个数组就足够了

我在这里对您的原始版本做了一些额外的调整(包括使用示例JSON端点):

更新日期:2013/08/30


selectedIndex错误是由“用户”模板中的HTML注释引起的。车把注释应为{{!}或{{!-->}。html注释导致在解析导致无法正确绑定到属性的模板时出现一些错误。App.controller不存在。您需要的是
这个。获取
,在
文本字段上,您应该使用
值绑定
,而不仅仅是值,否则数据绑定将无法工作
App.Users.reopenClass({
  findAll: function() {
    return $.getJSON("https://api.github.com/users/rjackson/repos", function(data) {
      return data.map(function(row) { return App.Users.create(row); });
    });
  }
});