我正在尝试解析RSS中的项目,但前提是它的标题中包含某些字符串。
我有一个Ember RSS解析器应用程序,可用作一个游戏的日志检查程序。例如,这里显示了一个名为“Versusik”的玩家的“冒险日志”:
http://alog.questscape.eu/#/logs/1/index
以下是从URL中抓取信息的代码,其中包含我正在使用的RSS源。
“feed.js”:
App.Feed = DS.Model.extend({
name: DS.attr('string'),
url: DS.attr('string'),
feedItems: DS.hasMany('App.FeedItem'),
refresh: function() {
var url = this.get('url');
var googleUrl = document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=http://services.runescape.com/m=adventurers-log/k=4/rssfeed?searchName=' + encodeURIComponent(url);
$.ajax({
url: googleUrl,
dataType: 'json',
context: this,
success: function(data) {
var feed = data.responseData.feed;
var items = feed.entries.forEach(function(entry) {
if(this.get('feedItems').findProperty('link', entry.link)) {
return;
}
var feedItem = this.get('feedItems').createRecord({
title: entry.title,
author: entry.author,
body: entry.content,
bodySnippet: entry.contentSnippet,
link: entry.link,
publishedDate: entry.publishedDate
});
}, this);
this.get('store').commit();
}
});
}
});
App.Feed.FIXTURES = [
{id: 1, name: 'Versusik', url: 'Versusik'},
{id: 2, name: 'Questalion', url: 'Questalion'},
{id: 3, name: 'Mokuin', url: 'Mokuin'},
{id: 4, name: 'Aiimer', url: 'Aiimer'},
{id: 5, name: 'Jakube33', url: 'Jakube33'},
{id: 6, name: 'Mordor Prime', url: 'Mordor_Prime'},
//...
//...it goes on for every Player I've specified...
//...
{id: 53, name: 'TooShortName', url: 'TooShortName'},
];
这是单项的代码。
“feed_item.js”:
App.FeedItem = DS.Model.extend({
title: DS.attr('string'),
author: DS.attr('string'),
content: DS.attr('string'),
contentSnippet: DS.attr('string'),
link: DS.attr('string'),
publishedDate: DS.attr('date'),
feed: DS.belongsTo('App.Feed')
});
App.FeedItem.FIXTURES = [];
它按预期工作,解析来自http://services.runescape.com/m=adventurers-log/rssfeed?searchName=("Name of player", you can try Versusik)
的数据并将其显示在我的ember应用程序中。
但是,如果我只想解析一个项目,如果它的标题包含字符串“dragon helm”(当完整项目标题说“我找到了龙头盔”时)该怎么办?
基本上我想创建类似的应用程序,但它只会解析这些字符串并将其放在像this这样的表中。
提前感谢您提供的任何帮助。
答案 0 :(得分:0)
但是如果我只想解析一个项目,如果它的标题包含字符串"龙头盔" (虽然完整的项目标题说"我找到了龙头舵")?
使用命名函数来分离关注点:
function foo(data)
{
/* feed data */
var feed = data.responseData.feed;
/* feed entry transformation */
var items = feed.entries.forEach(function(entry) {bar(entry, this)});
this.get('store').commit();
}
function bar(entry, that)
{
if(that.get('feedItems').findProperty('link', entry.link) == false)
{
return;
}
else
{
that.get('feedItems').createRecord({
title: entry.title,
author: entry.author,
body: entry.content,
bodySnippet: entry.contentSnippet,
link: entry.link,
publishedDate: entry.publishedDate
});
}
}
然后将条件检查添加到成功回调:
success: function(data) {
/* Test for "dragon helm" in stringified JSON */
if /dragon\shelm/.test(JSON.stringify(data))
{
foo(data);
}
}