如何消除此模板助手中的重复?

时间:2013-08-06 16:05:45

标签: coffeescript meteor handlebars.js

我有一个Meteor Handlebars模板助手,它代表了我的大部分模板助手,如下所示。

# Address Form Controls Template
Template.AddressFormControls.helpers
    address1: () ->
        if typeof Session.get('edit-building') is 'string'
            building = Buildings.findOne(Session.get('edit-building'))
            return building?.address?.address1

    address2: () ->
        if typeof Session.get('edit-building') is 'string'
            building = Buildings.findOne(Session.get('edit-building'))
            return building.address.address2

    city: () ->
        if typeof Session.get('edit-building') is 'string'
            building = Buildings.findOne(Session.get('edit-building'))
            return building.address.city

    state: () ->
        if typeof Session.get('edit-building') is 'string'
            building = Buildings.findOne(Session.get('edit-building'))
            return building.address.state

    zip_code: () ->
        if typeof Session.get('edit-building') is 'string'
            building = Buildings.findOne(Session.get('edit-building'))
            return building.address.zip_code

    main: () ->
        if typeof Session.get('edit-building') is 'string'
            building = Buildings.findOne(Session.get('edit-building'))
            return building?.phone?.main

    fax: () ->
        if typeof Session.get('edit-building') is 'string'
            building = Buildings.findOne(Session.get('edit-building'))
            return building?.phone?.fax

您会注意到每个帮助程序都包含一个if语句,以查看Session变量是否为字符串。如果它是一个字符串,那么它应该是一个可用于执行搜索所需对象的ID。

在整个项目中为人们使用的各种馆藏重复这样做似乎是一种浪费。

我该如何干这个?

帮助我Obiwan你是我唯一的希望!

1 个答案:

答案 0 :(得分:1)

你可以用

之类的东西缩短它

JS:

main:function() {
    building = Buildings.findOne({_id:Session.get('edit-building')}) 
    return building && building.phone && building.phone.main;
}

咖啡:

main: () ->
    building = Buildings.findOne(_id: Session.get("edit-building"))
    building and building.phone and building.phone.main

明确表示希望_id匹配的关键区别。因此,如果Session的{​​{1}}变量不存在,则不是字符串,也不匹配任何记录都不会返回。

这可能会缩短你的代码:

edit-building

然后在你的html(在AddressFormControls模板中)你可以这样做:

building: () ->
    Buildings.findOne(_id: Session.get("edit-building"))