简体   繁体   English

如何引用引导程序类型的数据?

[英]How to reference data for bootstrap-typeahead?

This is my data: 这是我的数据:

var markers = {
        "example": {"lat": -83.68088192646843, "lng": -125.270751953125, "type": "town"},
        "anotherexample": {"lat": -58.1548020417031, "lng": -21.318115234375, "type": "town"}
}

How do I reference this source of data? 如何引用此数据源?

Edit: 编辑:

The method is this: 方法是这样的:

$('.thing').typeahead({source: markers});

But that doesn't work and I think it's because markers isn't the correct syntax to select my markers object. 但这不起作用,我认为这是因为markers不是选择标记对象的正确语法。 What should I use instead? 我应该怎么用呢?

You could try to serialize the object in some ways. 您可以尝试以某些方式序列化对象。 In my example (jsfiddle) I concatenated each entry to obtain a certain string : 在我的示例(jsfiddle)中,我串联了每个条目以获得特定的字符串:

var markers_as_str = Array();
for(var index in markers) {
    var marker = markers[index];
    var str = index+" : "+marker.lat+" "+marker.lng+" "+marker.type;
    markers_as_str.push(str);
}

$('#strs').typeahead({
    source: markers_as_str
});

You could customize the matcher and sorter options to check specific properties. 您可以自定义matchersorter选项以检查特定属性。 But you would have difficulties with the display of the choices, so you'd have to override the updater option. 但是您在选择显示时会遇到困难,因此您必须覆盖updater选项。 And all this would go a bit too far, as you may not need it. 而且所有这些都可能有点过头,因为您可能不需要它。

I've used this: 我用了这个:

names = []; 
for (var k in markers) {
    if (markers.hasOwnProperty(k)) {
        names.push(k);
    }
}

I wrote a blog post on the matter, How to use rich objects and typed objects with Bootstrap Typeahead . 我写了一篇有关此问题的博客文章,“ 如何在Bootstrap Typeahead中使用富对象和类型化对象” The key is typing your objects to some class which has a toString() method to serialize and a fromString() method to deserialize (to be used in the Bootstrap Typeahead updater function to reference an object of the original type). 关键是将您的对象键入某个类,该类具有要序列化的toString()方法和要反序列化的fromString()方法(将在Bootstrap Typeahead updater函数中使用以引用原始类型的对象)。 In my blog, I use UsState as an example: 在我的博客中,我以UsState为例:

UsState.prototype.toString = function() {
    return JSON.stringify(this);
};

UsState.fromString = function(serializedState) {
    return $.extend(new UsState(), JSON.parse(serializedState));
};

Then in the Typeahead definition for updater : 然后在updater的Typeahead定义中:

updater: function(state) {
    state = UsState.fromString(state);
    $stateMessage.html('<strong>' + state.name + '</strong> has ' + state.numElectoralVotes + ' electoral votes.');
    return state.name;
},

Note the definition of other Typeahead methods to handle your objects properly: 请注意其他Typeahead方法的定义以正确处理您的对象:

highlighter: function(state) {
    return $.fn.typeahead.Constructor.prototype.highlighter.call(this, state.name);
},

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

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