花美男为中国互联网事业而奋斗

knockoutjs how to work - js

来源:未知 阅读(0)次 评论(0)

step 1

<script src="http://knockoutjs.com/downloads/knockout-3.4.1.js"></script>


step 2

/* common_ko.js */

(function (ko, module) {
    (function () {
        /*
         * 更改 "value" binding 的默认行为
         * 当value绑定的值发生改变时,在对应的element上trigger一个 'change' 事件
         * */
        var valueHandler = _.clone(ko.bindingHandlers.value)
        ko.bindingHandlers.value.init = function(element, valueAccessor) {
            if(valueAccessor() && _.isFunction(valueAccessor().subscribe)) {
                valueAccessor().subscribe(function () {
                    setTimeout(function () {
                        $(element).trigger('change')
                    }, 100)
                })
            }
            valueHandler.init.apply(this, arguments)
        }

        /*
         * 更改 "textInput" binding 的默认行为
         * 当textInput初始化和textInput绑定的值发生改变时,在对应的element上trigger一个 'change' 事件
         * */
        var textInputHandler = _.clone(ko.bindingHandlers.textInput)
        ko.bindingHandlers.textInput.init = function(element, valueAccessor) {
            if(valueAccessor()()) {
                setTimeout(function () {
                    $(element).trigger('change')
                }, 100)
            }
            if(valueAccessor() && _.isFunction(valueAccessor().subscribe)) {
                valueAccessor().subscribe(function () {
                    setTimeout(function () {
                        $(element).trigger('change')
                    }, 100)
                })
            }
            textInputHandler.init.apply(this, arguments)
        }
    })()
    /*
    * chosen 插件封装为custom binding
    * 具体用法参考web/src/static/tempaltes/rent_request.tpl.html中
    * */
    ko.bindingHandlers.chosen = {
        init: function(element, valueAccessor, allBindings)  {
            ko.bindingHandlers.options.init.call(this, element)
            $(element)[window.team.isPhone() ? 'chosenPhone' : 'chosen']({disable_search_threshold: 10, inherit_select_classes: true, disable_search: true, width: $(element).css('width')})
            if(allBindings().value && _.isFunction(allBindings().value.subscribe)) {
                allBindings().value.subscribe(function (val) {
                    if(!_.isObject(val)) {
                        $(element).val(val)
                    }
                    setTimeout(function () {
                        $(element).trigger('chosen:updated')
                    }, 100)
                })
            }
        },
        update: function(element, valueAccessor, allBindings) {
            ko.bindingHandlers.options.update.call(this, element, valueAccessor, allBindings)
            //如果直接触发chosen:updated,在更改time后再更改mode,chosen的更新有问题
            setTimeout(function () {
                $(element).trigger('chosen:updated')
            }, 100)
        }
    }


   
    /*
    * 日期选择控件 用法参考:web/src/property_to_rent_list.html:58
    * */
    ko.bindingHandlers.dateRangePicker = {
        init: function(element, valueAccessor)  {
            var dateAccessor,
                options,
                formatter = window.lang === 'en_GB'? 'DD-MM-YYYY': 'YYYY-MM-DD'
            if(_.isFunction(valueAccessor())) {
                dateAccessor = valueAccessor()
            } else {
                dateAccessor = valueAccessor().value
            }
            options = {
                autoClose: true,
                singleDate: true,
                format: formatter,
                showShortcuts: false,
                lookBehind: false,
                getValue: function() {
                    return dateAccessor() ? dateAccessor() : ''
                }
            }
            if(!_.isFunction(valueAccessor()) && valueAccessor().timeEnabled) {
                _.extend(options, {
                    startDate: window.moment().format(),
                })
            }
            $(element).find('input').dateRangePicker(options)
                .bind('datepicker-change', function (event, obj) {
                    //dateAccessor($.format.date(new Date(obj.date1), formatter))
                    $(event.target).val(window.moment(new Date(obj.date1)).format(formatter)).trigger('change')
                })
                .dateRangePickerCustom($(element).find('input'))
        }
    }

    /*
     * 日期选择输入框 用法参考:web/src/property_to_rent_list.html:59
     * */
    ko.bindingHandlers.dateInput = {
        init: function(element, valueAccessor)  {
            //date input format: http://stackoverflow.com/questions/7372038/is-there-any-way-to-change-input-type-date-format
            if($(element).is('input')) {
                $(element).on('touchstart', function () {
                    this.type = 'date'
                    $(this).focus()
                })
                $(element).siblings('label').on('touchstart', function () {
                    $(element)[0].type = 'date'
                    $(element).focus()
                })
                $(element).on('blur', function () {
                    if(this.value === '') {
                        this.type = 'text'
                    }
                })
            }
        }
    }

    // ......


    module.AppViewModel = function AppViewModel() {
        this.popupActive = ko.observable()
    }
    module.appViewModel = new module.AppViewModel()
    $(function () {
        ko.applyBindings(module.appViewModel)
    })
    $('body').on('touchmove', function (e) {
        //当手机上有弹出层时,禁止body滚动
        if(module.appViewModel.popupActive()) {
            e.stopImmediatePropagation()
        }
    })

    window.project.getEnum('suggestion_type')
        .then(function (val) {
            val = _.map(val, function (item) {
                item.slug = item.slug.replace(':suggestion', '')
                return item
            })
            module.suggestionTypeList = val
            module.suggestionTypeSlugList = _.map(val, function (item) {
                return item.slug
            })
        })

})(window.ko, window.currantModule = window.currantModule || {})


step 3   /scripts/rent_request.js

(function (ko) {

    window.openRentRequestForm = function (ticketId, isPopup) {
        var args = arguments
        if (window.user) {
            $.betterPost('/api/1/rent_intention_ticket/search', { interested_rent_tickets: ticketId, user_id: window.user.id})
                .done(function (data) {
                    var array = data
                    if (array && array.length > 0) {
                        window.dhtmlx.message({ type: 'error', text: window.i18n('您已经对此房源提交过咨询,如需继续咨询请您使用洋房东为您已匹配的邮件或短信系统沟通,谢谢。') })
                    } else {
                        $('body').trigger('openRentRequestForm', Array.prototype.slice.call(args))
                    }
                    $('.buttonLoading').trigger('end')

                })
                .fail(function (ret) {
                    window.dhtmlx.message({ type: 'error', text: window.getErrorMessageFromErrorCode(ret) })
                    $('.buttonLoading').trigger('end')
                })
        }
        else {
            $('body').trigger('openRentRequestForm', Array.prototype.slice.call(args))
            $('.buttonLoading').trigger('end')
        }
    }
    ko.components.register('chosen-referrer', {
        viewModel: function (params) {
            this.parentVM = params.vm
            this.list = ko.observableArray([])
            this.referrerText = ko.computed({
                read: function () {
                    return this.parentVM.referrerText()
                },
                write: function (value) {
                    this.parentVM.referrerText(value)
                }
            }, this)

            this.selectedReferrer = ko.observable()
            this.selectedReferrer.subscribe(function (value) {
                if(value === undefined) {
                    this.parentVM.referrer(value)
                    this.referrerText('')
                }
                if(_.find(this.list(), {id: value}) && _.find(this.list(), {id: value}).slug !== 'other') {
                    this.parentVM.referrer(value)
                    this.referrerText('')
                }
            }, this)
            this.parentVM.referrer.subscribe(function (value) {
                if(_.find(this.list(), {id: value})) {
                    this.selectedReferrer(_.find(this.list(), {id: value}).id)
                }
            }, this)
            this.parentVM.referrerText.subscribe(function (value) {
                if(value.length) {
                    this.selectedReferrer(_.find(this.list(), {slug: 'other'}).id)
                }
            }, this)
            window.project.getEnum('user_referrer')
                .then(_.bind(function (data) {
                    this.list(data)
                }, this))
        },
        template: { element: 'choseReferrer'}
    })


})(window.ko);




上一篇:Knockout.js入门 下一篇:JSON.parse()

相关推荐