简体   繁体   English

jQuery,克罗克福德关闭新手示例

[英]jQuery, Crockford Closures Newbie Example

There are hundreds of jQuery code snippets, trivial, arcane and sometimes wrong. 数百种jQuery代码片段,琐碎,晦涩甚至有时是错误的。 Rarely is there a self contained complete example. 很少有一个完整的例子。 Is this code using Crockford closures OK and correctly placed in the ready() function? 这段使用Crockford闭包的代码是否可以正确放置在ready()函数中? If not, how should it be improved or fixed? 如果没有,应该如何改进或修复? Is this overkill? 这是过度杀伤力吗? I'm trying to separate the user interface from the program logic which will eventually simulate a simple microcontroller. 我试图将用户界面与程序逻辑分离,该逻辑最终将模拟一个简单的微控制器。 This example increments a Program Counter when the Step button is pressed. 此示例在按下“步进”按钮时递增程序计数器。 It works OK. 可以。

// ==================================================================
$(document).ready(function(){
    // ==============================================================
    // The simulator code - NO UI CODE HERE
    // ==============================================================
    var sim = (function(){
        // Private vars
        var pc = 0;    // Program Counter

        // Public functions
        return {
            step: function(){
                pc += 1;
                return pc;
            }
        }
    }());
    // ==============================================================
    // jQuery UI Code - NO SIMULATOR CODE HERE
    // ==============================================================
    var ui = (function($){
        // Private vars
        var step = $('#step'),    // <button id="step">Step</button>
            pc   = $("#pc");      // <p id="pc">Program Counter = 0</p>

        // Private functions
        step.click(function() {
            pc.html('Program Counter = ' + sim.step());
        });
    }(jQuery));
});
// ==================================================================

Your code is very good example how application can be split between layers. 您的代码是一个很好的示例,说明如何在各个层之间拆分应用程序。 I don't like many indentations in the code - any intention seems to manage more logic. 我不喜欢代码中的许多缩进-任何意图似乎都可以管理更多逻辑。

Only a few changes 只有几处变化

$(init); // shortcut for $(document).ready()

function init() {
    // ==============================================================
    // The simulator code - NO UI CODE HERE
    // ==============================================================
    var sim = (function(){
        // Private vars
        var pc = 0;    // Program Counter

        // Public functions
        return {
            step: function(){
                return pc += 1;
            }
        }
    }());
    // ==============================================================
    // jQuery UI Code - NO SIMULATOR CODE HERE
    // ==============================================================
    var ui = (function(sim){
        // Private vars
        var $step = $('#step'), // variable with $ to mark than it contain jQuery collection
            $pc   = $("#pc");

        // Private functions
        $step.click(function() {
            $pc.html('Program Counter = ' + sim.step());
        });
    }(sim)); // pass sim as dependency
}

Variation with init method 初始化方法的变化

$(init);

function init() {
    var sim = simlulator();
    ui(sim);
}

function simlulator() {
    var pc = 0;

    return {
        step: function () {
            return pc += 1;
        }
    };
}

function ui(sim) {
    var $step = $('#step'),
        $pc = $("#pc");

    $step.click(function () {
        $pc.html('Program Counter = ' + sim.step());
    });
}

And some variation with two simulators: http://jsfiddle.net/vw9kN/ 还有两个模拟器的一些变化: http : //jsfiddle.net/vw9kN/

Based on this useful advice, here is a self-contained, complete and working version inside a namespace. 根据此有用的建议,这是命名空间内的一个独立,完整且有效的版本。 It can be split into separate source code files easily but here the separate files are combined into one. 可以轻松地将其拆分为单独的源代码文件,但此处将单独的文件合并为一个。

This is the quest for the "Holy Grail" of small-project, adequately structured, jQuery code, written so newbies might have some chance of understanding it and without a short cut for the .ready() function. 这是对小型项目,结构合理的jQuery代码的“圣杯”的追求,因此新手可能有一定的机会了解它,而没有.ready()函数的捷径。

http://jsfiddle.net/nbauers/pu4bK/27/ http://jsfiddle.net/nbauers/pu4bK/27/

Are we there yet? 我们到了吗?

// ==========================================
// Make a Name Space
// ==========================================
var myApp = myApp || {};
// ==========================================

// ==========================================
// simUI.js // User Interface Functionality
// ==========================================
myApp.ui = function (sim) {
    var $step     = $('#step'),        // A Button
        $assemble = $("#assemble"),    // A Button
        $source   = $("#source"),      // Source Text Area
        $lst      = $("#lst"),         // List Text Area
        $pc       = $("#pc");          // A Paragraph

    // ======================================
    // Single Step the Program
    // ======================================
    $step.click(function () {
        $pc.html('Program Counter = ' + sim.step());
    });
    // ======================================
    // Assemble the Source Code
    // ======================================
    $assemble.click(function () {
        $lst.val(sim.assemble($source.val()));
    });
    // ======================================
}
// ==========================================

// ==========================================
// simCore.js // Simulator Functionality
// ==========================================
myApp.simlulator = function() {
    var pc  = 0;

    var step = function () {
        return pc += 1;
    };

    var assemble = function(src) {
        step();
        return 'HELLO ' + pc + ' ' + src;
    };

    return {
        step:     step,        
        assemble: assemble
    };
}
// ==========================================

// ==========================================
// simInit.js // Initialise the environment
// ==========================================
myApp.init = function() {
    myApp.sim = myApp.simlulator();
    myApp.ui(myApp.sim);
}
// ==========================================
$(document).ready(function(){
    myApp.init();
});
// ==========================================

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM