在这种情况下,如何将对象作为变量传递给函数?我正在获取console.log(setup)= undefined?有没有更好的方法将回调函数传递给getTemplate()?谢谢

功能模板

function getTemplate (name, callback, dir) {
          if (dir === undefined) dir = ''
          var xhr = new XMLHttpRequest()
          var url = '/core/templates/' + dir + name + '.html'
          xhr.open('GET', url, true)
          xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
              var raw = xhr.responseText
              var compiled = Handlebars.compile(raw)
              callback(compiled)
            }
          }
          xhr.send()
        }


通话功能

for (var i = 0; i < item.length; i++) {
 var tabActive = ''
 if (i == 0) { tabActive = 'active' }

 var tab = item[i],
 tabId = tab.id,
 tabTitle = tab.title,
 variables = {tabActive: tabActive, tabId: tab.id, tabTitle: tab.title}

 console.log(variables) // *A increments 5328, 5329

 getTemplate('tab-nav', function (tmp) {

 console.log(variables) // *B increments 5328, 5328

 $(tabNavigationId + '>ul').append(tmp(variables))

 })

}


*一个

index.js:18 Object {tabActive: "active", tabId: "5327", tabTitle: "User Experience"}
index.js:18 Object {tabActive: "", tabId: "5328", tabTitle: "Design"}
index.js:18 Object {tabActive: "", tabId: "5329", tabTitle: "Web Development"}
index.js:18 Object {tabActive: "", tabId: "5330", tabTitle: "Mobile Development"}


* B

index.js:21 Object {tabActive: "", tabId: "5743", tabTitle: "Extension Settings"}
index.js:21 Object {tabActive: "", tabId: "5743", tabTitle: "Extension Settings"}
index.js:21 Object {tabActive: "", tabId: "5743", tabTitle: "Extension Settings"}
index.js:21 Object {tabActive: "", tabId: "5743", tabTitle: "Extension Settings"}


从getTemplate'tmp'进行回调

function ret(context, execOptions) {
        if (!compiled) {
          compiled = compileInput();
        }
        return compiled.call(this, context, execOptions);
      }

最佳答案

您不能在回调函数中传递变量。

您需要将其用作

var setup = {tabActive: tabActive, tabId: tab.id, tabTitle: tab.title}

getTemplate('tab-nav', function (tmp) {
  //setup is accessible here
  console.log(setup)
  $(tabNavigationId + '>ul').append(tmp(setup))
})


-新的更新-

您的getTemplate函数function getTemplate (name, callback, dir) {
期望第二个参数是一个回调函数。
因此,您需要做的是,使用getTemplate函数作为

getTemplate('tab-nav', myCallBackFunc, 'dir');


那么myCallBackFunc将会是这样。

我可以看到您正在使用某些参数调用回调。

function myCallBackFunc(response) {
 //do something with response
}


另外,您还没有定义有关tmp函数的任何内容

关于javascript - 将对象传递给功能JS,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43012652/

10-11 13:27