简体   繁体   中英

how to refer to a fancytree variable from another function in javascript

I'm trying to modularise my javascript. I'm not new to JS, but I my knowledge is not as advanced as some. This is probably an easy question for someone who's good at 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'? 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.

/**
 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. But for whatever reason fancytree tree plugin doesn't return the instance of itself when it's initialised. A little strange.

So the actual fix for this particular issue was to use this function from the 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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