zoukankan      html  css  js  c++  java
  • 两个有关Knockout自定义拓展方法fn的小技巧

    Adding custom functions using "fn"

    让observable自增/自减

    1. 最简单的方法是self.num(self.num() + 1), 但是这个写起来比较麻烦.

    2. 一种方法是拓展observable的方法, 增加incrementdecrement方法:

    ko.observable.fn.increment = function (value) {
        this(this() + (value || 1));
    };
    ko.observable.fn.decrement = function (value) {
        this(this() + (value || 1));
    };
    

    这样用起来简单多了. self.num.increment(3)就可以让self.num自增3.

    1. 还有一种方法, 可以对某些observable拓展其方法而不影响其他的observable.
    ko.extenders['incrementable'] = function (target, enabled) {
        if (enabled) {
            target.increment = function (incValue) {
                this(this() + (incValue || 1));
            }.bind(target);
        }
        return target;
    };
    var num = ko.observable(0).extend({ incrementable: true });
    num.increment();
    

    参考: Increment a KnockoutJS observable in an good expressive way

    subscribe的时候触发callback

    很多时候我们在给observable注册(subscribe)回调函数(callback)的时候, 想同时触发一次callback. 但是subscribe只在observable变化之后才会触发callback, 注册的时候不会触发. 这时我们可以在subscribable上创建一个方法来达到这个目的.

    ko.subscribable.fn.callAndSubscribe = function (callback) {
        this.subscribe(callback);
        callback();
    }
    self.num.callAndSubscribe(function() { /*...*/ })
    
  • 相关阅读:
    视频像素点级的标注
    unet
    Emmet缩写语法
    Nginx漏洞利用与安全加固
    算法时间复杂度
    动态规划dp
    数据结构Java实现04---树及其相关操作
    关于递归
    Java正则表达式
    Java String相关
  • 原文地址:https://www.cnblogs.com/7z7chn/p/5184046.html
Copyright © 2011-2022 走看看