将对象传递给函数JS

时间:2017-03-25 04:49:48

标签: javascript jquery

如何将对象作为变量传递给此方案中的函数?我收到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))

 })

}

* A

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);
      }

2 个答案:

答案 0 :(得分:0)

您无法在回调函数中传递变量。

您需要将其用作

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功能

的任何内容

答案 1 :(得分:-2)

如果你想要一个变量来存储一个对象,我想你应该选择JSON。然后,您可以使用JSON.parse()从JSON数据中解析和提取您的信息。请查看w3schools.org了解更多详细说明。 :)

相关问题