简体   繁体   English

如何从javascript中的另一个函数引用fancytree变量

[英]how to refer to a fancytree variable from another function in javascript

I'm trying to modularise my javascript. 我正在尝试模块化我的JavaScript。 I'm not new to JS, but I my knowledge is not as advanced as some. 我对JS并不陌生,但是我的知识不如某些知识先进。 This is probably an easy question for someone who's good at JS. 对于精通JS的人来说,这可能是一个简单的问题。

In the code below - how can I get a handle to the fancytree that's created in the 'handleTreeBrowser' function, I need the reference in the success function of the 'newTopCategoryForm'? 在下面的代码中-如何获取在'handleTreeBrowser'函数中创建的花式树的句柄,我需要'newTopCategoryForm'的成功函数中的引用吗? Is there a better option than just creating the variable in a higher scope? 是否有比仅在更高范围内创建变量更好的选择?

I tried just searching for the element via JQuery thinking it would already be embelished with the fancytree properties & methods etc...but the reload function is undefined. 我试图通过JQuery搜索元素,以为它已经被fancytree属性和方法等所修饰...但是重载函数未定义。

/**
 The edit related products page controls
 **/
var ManageCategories = function () {

    var handleFormButtons = function () {

        console.debug('initialising buttons...');
        $(document).on('click','.new-topcategory-button', function(event)
        {
            event.preventDefault ? event.preventDefault() : event.returnValue = false;
            console.debug('clicked...');
            console.debug($(this).attr('href'));

            var refreshURI = $(this).attr('href');
            $.get(refreshURI)
                .success(function(data,status,xhr){
                    // need to do something with the data here.
                    $('#categoryFormContainer').html(data);
                    RichText.init();
                });

        })
    };

    var handleNewTopCategoryForm = function () {
        console.debug('initialising top category form');
        $(document).on('submit', '#topCategoryForm', function(event)
            {
                console.debug("submitting the new top category form");
                var form = $(this);
                var token = $("meta[name='_csrf']").attr("content");
                var header = $("meta[name='_csrf_header']").attr("content");
                var formData = form.serializeArray();

                $(this).find('button').attr('disabled');


                event.preventDefault ? event.preventDefault() : event.returnValue = false;

                var jqxhr = $.ajax(
                    {
                        url: form.attr('action'),
                        type: 'POST',
                        data: formData,
                        headers: {'X-CSRF-TOKEN': token}
                    }
                )
                    .success(function (data, status, xhr) {
                        var messageContainer = $('#messageContainer');
                        var source = $('#ui_message_template').html();
                        var template = Handlebars.compile(source);
                        var html = template(data);
                        messageContainer.html(html);
                        data.form = form;

                        // Reload the tree from previous `source` option
                        $('#tree').reload().done(function(){
                            alert("reloaded");
                        });

                        // we trigger this publish method so the browser can update itself
                        $.Topic( 'topCategoryAdded' ).publish( data );


                    })
                    .fail(function (data, status, xhr) {
                        var messageContainer = $('#messageContainer');
                        var source = $('#ui_message_template').html();
                        var template = Handlebars.compile(source);
                        var html = template(data);
                        messageContainer.html(html);

                        // we have to process the form validation failures here.

                    });
            }

        );


    }

    var handleTreeBrowser = function () {
        console.debug('initialising trees.');
        $('#tree').fancytree({
            source: {
            url: '/admin/categories/json/full_category_tree',
            cache: false
            },
            extensions: ["dnd"],
            checkbox: false,
            selectMode: 2,
            activate: function(event, data) {
                console.debug(event);
                console.debug(data);
                console.debug(data.node.key())
            },
            dnd: {
                autoExpandMS: 400,
                focusOnClick: true,
                preventVoidMoves: true, // Prevent dropping nodes 'before self', etc.
                preventRecursiveMoves: true, // Prevent dropping nodes on own descendants
                dragStart: function(node, data) {
                    /** This function MUST be defined to enable dragging for the tree.
                     *  Return false to cancel dragging of node.
                     */
                    return true;
                },
                dragEnter: function(node, data) {
                    /** data.otherNode may be null for non-fancytree droppables.
                     *  Return false to disallow dropping on node. In this case
                     *  dragOver and dragLeave are not called.
                     *  Return 'over', 'before, or 'after' to force a hitMode.
                     *  Return ['before', 'after'] to restrict available hitModes.
                     *  Any other return value will calc the hitMode from the cursor position.
                     */
                    // Prevent dropping a parent below another parent (only sort
                    // nodes under the same parent)
                    /*           if(node.parent !== data.otherNode.parent){
                     return false;
                     }
                     // Don't allow dropping *over* a node (would create a child)
                     return ["before", "after"];
                     */
                    return true;
                },
                dragDrop: function(node, data) {
                    /** This function MUST be defined to enable dropping of items on
                     *  the tree.
                     */
                    data.otherNode.moveTo(node, data.hitMode);
                }

            }

        });

    }




    return {
        //main function to initiate the module
        init: function () {

            handleTreeBrowser();
            handleFormButtons();
            handleNewTopCategoryForm();


        }
    };
}();

Actually the previous answer would normally be fine generally for javascript so I'll leave it as okay. 实际上,以前的答案通常对于javascript通常来说是可以的,所以我将其保留为正常。 But for whatever reason fancytree tree plugin doesn't return the instance of itself when it's initialised. 但是无论出于何种原因,fancytree树插件在初始化时都不会返回其自身的实例。 A little strange. 有点奇怪。

So the actual fix for this particular issue was to use this function from the fancytree api. 因此,针对此特定问题的实际解决方法是使用fancytree api中的此功能。

// from handleform.success
// Reload the tree from previous `source` option
var tree = $("#tree").fancytree('getTree');
tree.reload().done(function(){
    alert("reloaded");
});

You can declare fancytree variable in the function and the js closure will allow you to access it from the other functions: 您可以在函数中声明fancytree变量,而js闭包将允许您从其他函数访问它:

var ManageCategories = function () {
    var fancytree = null;
    // in handleform.success:
        if (fancytree !== null)
            fancytree....
    // in handleTreeBrowser:
        fancytree = $("#tree').fancytree(....

this fancytree is only accessible by those 2 functions. 只有这两个功能才能访问该花式树。

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

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