Writing custom controls in Sproutcore 2

北城以北 提交于 2019-12-04 13:36:55

It sounds like you want to loop through a list of objects and create links that, when clicked, calls some JavaScript code that has access to the original objects.

At the moment, the easiest way to do that is to bind the template context to a new custom view. You can see everything in action at this JSFiddle: http://jsfiddle.net/67GQb/

Template:

{{#each App.people}}
    {{#view App.PersonView contentBinding="this"}}
    <a href="#">{{content.fullName}}</a>
    {{/view}}
{{/each}}

App Code:

App = SC.Application.create();

App.Person = SC.Object.extend({
    fullName: function() {
        return this.get('firstName') + ' ' + this.get('lastName');
    }.property('firstName', 'lastName') 
});

App.people = [
    App.Person.create({ firstName: "Yehuda", lastName: "Katz" }),
    App.Person.create({ firstName: "Tom", lastName: "Dale" })
];

App.PersonView = SC.View.extend({
    mouseDown: function() {
        // Note that content is bound to the current template
        // context in the template above.
        var person = this.get('content');
        alert(person.get('firstName'));
    }
});

That said, we understand that this is a bit cumbersome, and have some ideas for further streamlining the process that we will be working on in the upcoming weeks.

Here's are list of demo apps.

http://blog.sproutcore.com/announcing-the-winners-of-the-demo-apps-contest/

Here's a plug for my own open source demo app that I entered - chililog. I'm blogging about how I've used sproutcore at the blog.chililog.org.

Hope this helps.

An alternative way to achieve what Yehuda is doing above is to use the #collection directive:

Template code:

{{#collection App.PeopleView contentBinding="App.people"}}
    <a href="#">{{content.fullName}}</a>
{{/collection}}

App Code:

App = SC.Application.create();

App.Person = SC.Object.extend({
    fullName: function() {
        return this.get('firstName') + ' ' + this.get('lastName');
    }.property('firstName', 'lastName') 
});

App.people = [
    App.Person.create({ firstName: "Yehuda", lastName: "Katz" }),
    App.Person.create({ firstName: "Tom", lastName: "Dale" })
];

App.PeopleView = SC.CollectionView.extend({
    itemViewClass: SC.View.extend({
        mouseDown: function() {
            var person = this.get('content');
            alert(person.get('firstName'));
        }
    })
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!